package cn.col.gszf.handler;

import cn.col.gszf.model.RestResult;
import cn.col.gszf.util.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @Description 身份验证入口
* @Author: wanghong
* @Date: 2024/6/17
*/
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
    * @Description 判断用户是否登录
    * @Param: HttpServletRequest,HttpServletResponse,AuthenticationException
    * @Author: wanghong
    * @Date: 2024/6/17
    */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        if(isAjaxRequest(httpServletRequest)){
            ResponseUtil.restResponse(httpServletResponse, HttpStatus.UNAUTHORIZED, RestResult.error(401, "请先登录"));
        }else{
            httpServletResponse.setStatus(401);
            httpServletResponse.sendRedirect("/login");
        }

    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}
